package com.taichuan.keysupport;

import android.view.View;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by OISNY on 2016/8/22.
 */
public class ViewFocus {
    int posFocus = 0;
    View currentFocus;
    List<View> viewFocusList = new ArrayList<View>();

    public void add(View v) {
        v.setFocusable(true);
        v.setFocusableInTouchMode(true);
        viewFocusList.add(v);
    }

    public void add(View v, int position) {
        if (!viewFocusList.contains(v)) {
            v.setFocusable(true);
            v.setFocusableInTouchMode(true);
            viewFocusList.add(position, v);
        }
    }

    public int remove(View v) {
        if (viewFocusList.contains(v)) {
            v.setFocusable(false);
            v.setFocusableInTouchMode(false);
            int position = viewFocusList.indexOf(v);
            viewFocusList.remove(v);
            return position;
        }
        return viewFocusList.size();
    }

    public void removeAll() {
        posFocus = 0;
        viewFocusList.clear();
    }

    public void requestFocus(int pos) {
        if (viewFocusList.size() > pos) {
            posFocus = pos;
            currentFocus = viewFocusList.get(posFocus);
            currentFocus.requestFocus();
        }
    }

    public void requestFocus(View view) {
        if (viewFocusList.contains(view)) {
            posFocus = viewFocusList.indexOf(view);
            currentFocus = viewFocusList.get(posFocus);
            currentFocus.requestFocus();
        }
    }

    public void nextFocus() {
        if (posFocus < (viewFocusList.size() - 1)) {
            posFocus++;
        } else {
            posFocus = 0;
        }
        currentFocus = viewFocusList.get(posFocus);
        currentFocus.requestFocus();
    }

    public void forwardFocus() {
        if (posFocus > 0) {
            posFocus--;
        } else {
            posFocus = 0;
        }
        currentFocus = viewFocusList.get(posFocus);
        currentFocus.requestFocus();
    }

    public int getCurrentFocus() {
        return posFocus;
    }

    public int size() {
        return viewFocusList.size();
    }

    public boolean onFocused(View view) {
        return view == currentFocus;
    }

    public boolean hasView(View view) {
        return viewFocusList.contains(view);
    }

    public void upFocus() {
        if (posFocus > 0) {
            posFocus--;
        } else {
            posFocus = viewFocusList.size() - 1;
        }
        currentFocus = viewFocusList.get(posFocus);
        currentFocus.requestFocus();
    }

    public void handleClick() {
        if (currentFocus != null) {
            currentFocus.performClick();
        }
    }
}
